// pages/publish/publish.js
import { Topic } from "../../model/Topic";
import { Upload } from "../../model/Upload"
const topic = new Topic();
const upload = new Upload();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navState: false,
        selectedNavTxt: "选择主题",
        tempFilePaths: [],
        sourceType: 0,
        chooseImgNum: 0,
        categories: [],
        startTime: '',
        endTime: '',
        voteItems: [{
                text: "",
                image: ""
            },
            {
                text: "",
                image: ""
            }
        ],
        pulishCon: {
            categoryId: "",
            content: "",
            images: "",
            videos: "",
            location: "",
            voteInfo: {
                type: 1,
                expire: "",
                items: []
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this._getCategoryList();
        this._initTime();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    /**
     * 初始化时间
     */
    _initTime() {
        const date = new Date();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate() + 1;
        const startTime = `${year}-${month}-${day}`;
        date.setMonth(month);
        const endYear = date.getFullYear();
        const endMonth = date.getMonth() + 1;
        const endDay = date.getDate();
        const endTime = `${endYear}-${endMonth}-${endDay}`;
        this.setData({
            startTime: startTime,
            endTime: endTime
        });
    },
    /**
     * 请求帖子的分类
     */
    _getCategoryList() {
        const that = this;
        topic.getCategoryList()
            .then(res => {
                let categoryList = res.data.Results.map(catery => {
                    catery.selected = false;
                    return catery;
                });
                that.setData({
                    categories: categoryList
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 选择帖子主题
     */
    selecttap() {
        this.setData({
            navState: true
        });
    },
    /**
     * 点击分类按钮
     */
    navtap(e) {
        const id = e.currentTarget.dataset.id;
        let navTxt = "";
        let categories = this.data.categories.map(category => {
            if (category.CategoryId == id) {
                category.selected = true;
                navTxt = category.Name
            } else {
                category.selected = false;
            }
            return category;
        });
        this.setData({
            categories: categories,
            navState: false,
            ['pulishCon.categoryId']: id,
            selectedNavTxt: navTxt
        });
    },
    /**
     * 监听内容输入
     */
    listenContent(e) {
        this.setData({
            ['pulishCon.content']: e.detail.value
        });
    },
    /**
     * 选择图片
     */
    selectImg() {
        wx.chooseImage({
            count: 9 - this.data.chooseImgNum,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (result) => {
                let files = result.tempFilePaths.map(file => {
                    let objfile = {};
                    objfile.type = 1;
                    objfile.url = file;
                    return objfile;
                });
                this.setData({
                    tempFilePaths: this.data.tempFilePaths.concat(files),
                    sourceType: 1,
                    chooseImgNum: this.data.chooseImgNum + files.length
                });
                if (this.data.chooseImgNum >= 9) {
                    this.setData({
                        sourceType: 3
                    });
                }
            },
            fail: (err) => {
                if (err.errMsg === "chooseImage:fail cancel") {
                    wx.showToast({
                        title: '取消选择',
                        icon: "none"
                    })
                } else {
                    wx.showToast({
                        title: '微信接口调用失败',
                        icon: "none"
                    })
                }
            }
        });
    },
    /**
     * 删除图片
     */
    delete(e) {
        const index = e.currentTarget.dataset.index;
        let tempFiles = this.data.tempFilePaths;
        tempFiles.splice(index, 1);
        if (tempFiles.length <= 0) {
            this.setData({
                sourceType: 0
            });
        }
        if (tempFiles.length >= 1) {
            this.setData({
                sourceType: 1
            });
        }
        this.setData({
            tempFilePaths: tempFiles
        });
    },
    /**
     * 选择视频
     */
    chooseVideo() {
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            compressed: true,
            maxDuration: 20,
            success: (res) => {

                if (res.duration > 20) {
                    wx.lin.showDialog({
                        type: "alert",
                        title: "提示",
                        content: "视频长度不能大于20s",
                        success: (res) => {}
                    })
                    return false;
                }
                let objfile = {
                    type: 2,
                    url: res.tempFilePath,
                    thumb: res.thumbTempFilePath
                }
                this.setData({
                    sourceType: 3,
                    tempFilePaths: [objfile]
                });
            },
            fail: (err) => {
                if (err.errMsg === "chooseImage:fail cancel") {
                    wx.showToast({
                        title: '取消选择',
                        icon: "none"
                    })
                } else {
                    wx.showToast({
                        title: '微信接口调用失败',
                        icon: "none"
                    })
                }
            }
        });
    },
    /**
     * 添加新的投票选项
     */
    addVote() {
        const votes = this.data.voteItems;
        votes.push({
            text: "",
            image: ""
        })
        this.setData({
            voteItems: votes
        });
    },
    /**
     * 删除投票选项
     */
    delVote(e) {
        const index = e.currentTarget.dataset.index;
        let votes = this.data.voteItems;
        votes.splice(index, 1);
        this.setData({
            voteItems: votes
        });
    },
    /**
     * 输入投票选项
     */
    voteinput(e) {
        const index = e.currentTarget.dataset.index;
        const value = e.detail.value;
        let votes = this.data.voteItems;
        votes[index]['text'] = value;
        this.setData({
            voteItems: votes
        });
    },
    /**
     * 选择投票选项图片
     */
    selectVoteImg(e) {
        const index = e.currentTarget.dataset.index;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (result) => {
                let votes = this.data.voteItems;
                let tempFilePath = result.tempFilePaths[0];
                wx.showLoading({
                    title: "上传中"
                });
                upload.upload([{
                        url: tempFilePath
                    }])
                    .then(res => {
                        wx.hideLoading();
                        let file = JSON.parse(res[0]['data'])['data']['url'];
                        votes[index]['image'] = file
                        this.setData({
                            voteItems: votes
                        });
                    })
                    .catch(err => {
                        wx.showToast({
                            title: err.msg,
                            icon: "none"
                        });
                    });
            },
            fail: (err) => {
                if (err.errMsg === "chooseImage:fail cancel") {
                    wx.showToast({
                        title: '取消选择',
                        icon: "none"
                    })
                } else {
                    wx.showToast({
                        title: '微信接口调用失败',
                        icon: "none"
                    })
                }
            }
        });
    },
    /**
     *删除投票图片
     * @param {*} e 
     */
    delVotePic(e) {
        const index = e.currentTarget.dataset.index;
        let votes = this.data.voteItems;
        votes[index]['image'] = "";
        this.setData({
            voteItems: votes
        });
    },
    /**
     * 多选框改变
     */
    switchChange(e) {
        if (e.detail.value) {
            this.setData({
                ['pulishCon.voteInfo.type']: 2
            });
        } else {
            this.setData({
                ['pulishCon.voteInfo.type']: 1
            });
        }
    },
    /**
     * 选择截止时间
     */
    bindDateChange(e) {
        this.setData({
            ['pulishCon.voteInfo.expire']: e.detail.value
        });
    },
    /**
     *选择地址
     */
    chooseMap() {
        const that = this;
        wx.getSetting({
            success (res) {
                if(res.authSetting["scope.userLocation"]===false){
                    wx.openSetting();
                }
                wx.chooseLocation({
                    success: (res) => {
                        that.setData({
                            ['pulishCon.location']: res.name
                        });
                    },
                    fail: (err) => {
                        
                    },
                    complete: () => {}
                });
            }
          })
    },
    /**
     * 发布内容
     */
    publish() {
        if (!wx.getStorageSync("isauth")) {
            wx.navigateTo({
                url: '/pages/login/login',
            });
            return false;
        }
        if (!this.data.pulishCon.categoryId) {
            wx.showToast({
                title: "请选择主题",
                icon: "none"
            });
            return false;
        }
        if (this.data.pulishCon.content == "" && this.data.pulishCon.images == "" && this.data.pulishCon.videos == "") {
            wx.showToast({
                title: "帖子内容不能为空哦~",
                icon: "none"
            });
            return false;
        }
        if (this.data.pulishCon.categoryId == 2) {
            var num = 0;
            this.data.voteItems.forEach((vote, index) => {
                if (vote.text == "" && vote.image == "") {
                    ++num;
                }
            });
            if (num > 0) {
                wx.showToast({
                    title: `选项不能为空`,
                    icon: "none"
                });
                return false;
            }
            if (this.data.pulishCon.voteInfo.expire == "") {
                wx.showToast({
                    title: "请选择投票截止时间",
                    icon: "none"
                });
                return false;
            }
        }
        this.setData({
            ['pulishCon.voteInfo.items']: this.data.voteItems
        });
        wx.showLoading({
            title: "发布中"
        })
        if (this.data.tempFilePaths.length <= 0) {
            this._subinfo();
        } else {
            upload.upload(this.data.tempFilePaths)
                .then(res => {
                    let fileUrls = [];
                    res.forEach((file) => {
                        let fileData = JSON.parse(file.data);
                        fileUrls.push(fileData.data.url);
                    });
                    if (res.length > 1) {
                        this.setData({
                            ['pulishCon.images']: fileUrls.join(',')
                        });
                    } else {
                        if (this.data.sourceType == 1) {
                            this.setData({
                                ['pulishCon.images']: fileUrls.join(',')
                            });
                        } else {
                            this.setData({
                                ['pulishCon.videos']: fileUrls.join(',')
                            });
                        }
                    }
                    this._subinfo();
                })
                .catch(err => {
                    wx.showToast({
                        title: err.message,
                        icon: "none"
                    });
                });
        }

    },
    /**
     * 提交帖子
     */
    _subinfo() {
        let pulishCon = this.data.pulishCon;
        topic.publish(pulishCon)
            .then(res => {
                wx.showToast({
                    title: "提交成功"
                });
                wx.hideLoading();
                this.setData({
                    selectedNavTxt: "选择主题",
                    tempFilePaths: [],
                    sourceType: 0,
                    chooseImgNum: 0,
                    ['pulishCon.categoryId']: 0,
                    ['pulishCon.content']: "",
                    ['pulishCon.images']: "",
                    ['pulishCon.videos']: "",
                    ['pulishCon.location']: "",
                    ['pulishCon.voteInfo']: {
                        type: 1,
                        items: [],
                        expire: ""
                    },
                    voteItems: [{
                            text: "",
                            image: ""
                        },
                        {
                            text: "",
                            image: ""
                        }
                    ]
                });
                setTimeout(() => {
                    wx.switchTab({
                        url: '/pages/index/index'
                    });
                    wx.setStorageSync("pullDown", true);
                }, 500);
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                });
            });
    },
    /**
     * 点击帖子列表的阴影部分
     */
    navShadow() {
        this.setData({
            navState: false
        });
    }

})